﻿NExt.bind = function(config, object) {
    if (!config)
        return;

    if (config.isBinding)
        return;

    if (object.isBinded)
        return;
    object.isBinded = true;

    if (!(config.vars))
        return;

    config.isBinding = true;

    var variables = new Ext.util.MixedCollection();

    for (var i = 0; i < config.vars.length; i++) {
        var varName = config.vars[i].Key;
        var varId = config.vars[i].Value;
        variables.add(varId, { 'parent': object, 'name': varName });
    }

    resolveVariables = function(variables, config, object) {
        if (object.varId) {
            varModel = variables.get(object.varId);
            //TODO: VarModel undefined durumu..
            if (varModel)
                varModel.instance = object;
        }

        for (var field in config) {
            if (field == "vars")
                continue;

            if (field == "xtype")
                continue;

            // TODO: Neden rightSetter ise "too much recursion" hatasi veriyor... düzeltilmesi gerekiyor.
            if (field == "rightSetter")
                continue;

            if (field == "isBinding")
                continue;

            if (field == "listeners")
                continue;

            var itemConfig = config[field];
            var itemObject = object[field];

            if (typeof itemObject != "object")
                continue;

            if (itemObject instanceof Array) {
                for (var i = 0; i < itemObject.length; i++) {
                    var arrayItemConfig = itemConfig[i];
                    var arrayItemObject = itemObject[i];
                    resolveVariables(variables, arrayItemConfig, arrayItemObject);
                }
                continue;
            }

            if (itemObject instanceof Ext.util.MixedCollection) {
                for (var i = 0; i < itemObject.length; i++) {
                    var arrayItemConfig = itemConfig[i];
                    var arrayItemObject = itemObject.get(i);
                    resolveVariables(variables, arrayItemConfig, arrayItemObject);
                }
                continue;
            }

            resolveVariables(variables, itemConfig, itemObject);
        }
    };

    resolveVariables(variables, config, object);

    for (var i = 0; i < variables.length; i++) {
        varModel = variables.get(i);

        if (typeof (varModel.instance) == 'undefined')
            alert('Can not get variable named [' + varModel.name + '] from type [' + config.xtype + ']');

        varModel.parent[varModel.name] = varModel.instance;
        varModel.instance['parent'] = varModel.parent;
    }

    config.isBinding = false;
}
